package com.ifdom.objecttype;

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

/**
 * 弱引用-垃圾回收验证
 * 基础类型数据不会被回收
 *
 * @Author ifredomvip@gmail.com
 * @Date 2022/9/30 11:10
 * @Version 1.0.0
 * @Description
 **/
public class WeakReferenceDemo {
    public static void main(String[] args) {

        ReferenceQueue<WeakBasicObject> destroyedReference = new ReferenceQueue<>();

        String str = "abc";
        WeakReference<String> weakReference1 = new WeakReference<>(str);


        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("qpm");
        WeakReference<StringBuffer> weakReference2 = new WeakReference<>(stringBuffer);


        WeakBasicObject object = new WeakBasicObject("abc");
        WeakReference<WeakBasicObject> weakReference3 = new WeakReference<>(object, destroyedReference);

        System.out.println("WeakBasicObjectQueue 中：" + destroyedReference.poll());

        // 查看弱引用对象中，存储得强引用对象
        System.out.println(weakReference1.get());
        System.out.println(weakReference2.get());
        System.out.println(weakReference3.get());

        Reference<? extends WeakBasicObject> r1 = null;

        while ((r1 = destroyedReference.poll()) != null) {
            //不会输出，因为没有回收被弱引用的对象，并不会加入队列中
            System.out.println("r1: " + r1);
        }

        str = null;
        stringBuffer = null;
        object = null;

        System.gc();

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(weakReference1.get()); // abc
        System.out.println(weakReference2.get()); // null
        System.out.println(weakReference3.get()); // null

        Reference<? extends WeakBasicObject> r2 = null;

        System.out.println("WeakBasicObjectQueue 中：" + destroyedReference.poll());

    }
}


class WeakBasicObject {
    private String name;

    public WeakBasicObject(String name) {
        this.name = name;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("触发回收");
    }

    @Override
    public String toString() {
        return "WeakBasicObject{" +
                "name='" + name + '\'' +
                '}';
    }
}